package org.yu.api.register;

import io.netty.buffer.Unpooled;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.network.NetworkHooks;

import javax.annotation.Nonnull;
import java.util.function.Supplier;

public class MenuHolder<T extends AbstractContainerMenu> implements Supplier<MenuType<T>> {
    public Supplier<MenuType<T>> type;

    @Override
    public MenuType<T> get() {
        return type.get();
    }

    public void open(Player player, Component title, BlockPos pos) {
        if (player instanceof ServerPlayer serverPlayer) {
            MenuProvider containerProvider = new MenuProvider() {
                @Nonnull
                @Override
                public Component getDisplayName() {
                    return title;
                }

                @Override
                public AbstractContainerMenu createMenu(int containerId, @Nonnull Inventory inventory, @Nonnull Player player) {
                    FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.buffer());
                    buffer.writeBlockPos(pos);
                    return type.get().create(containerId, inventory, buffer);
                }
            };
            NetworkHooks.openGui(serverPlayer, containerProvider, pos);
        }
    }
    public  void openItemMenu(@Nonnull ServerPlayer player, InteractionHand hand) {
        boolean isMainHand= hand == InteractionHand.MAIN_HAND;
        var itemStack=player.getItemInHand(hand);
        MenuProvider containerProvider = new MenuProvider() {

            @Nonnull
            @Override
            public Component getDisplayName() {
                return itemStack.getDisplayName();
            }

            @Override
            public AbstractContainerMenu createMenu(int containerId, @Nonnull Inventory inventory, @Nonnull Player player) {
                var buffer= new FriendlyByteBuf(Unpooled.buffer());
                buffer.writeBoolean(isMainHand);
                return type.get().create(containerId, inventory,buffer);
            }
        };
        NetworkHooks.openGui(player, containerProvider,buffer->buffer.writeBoolean(isMainHand));
    }
    public void open(ServerPlayer player, BlockPos pos) {
        open(player, new TranslatableComponent("menu." + type.get().getRegistryName().toString().replace(':', '.')), pos);
    }
}
